<template>
  <div class="container">
    <a-page-header :style="{ background: 'var(--color-bg-2)' }" title="Quotation Form">
      <template #extra>
        <a-button type="secondary" class="btn" :loading="loading" @click="handleSendEmail">
          Send quotation to my Email.
        </a-button>
      </template>
    </a-page-header>

    <a-layout id="quotation-content">
      <div ref="refPdf">
        <a-layout>
          <!--content-->
          <a-layout-content style="width: 1400px; margin: 0 auto">
            <a-space direction="vertical" style="padding: 30px" :loading="loading" fill>
              <a-card>
                <!--customer info-->
                <h1 style="font-size: 24px" class="line">
                  <div>QUOTATION FORM</div>
                </h1>
                <!-- 报价基本信息 -->
                <a-descriptions layout="vertical" size="large" :column="3" bordered>
                  <a-descriptions-item label="Quote to"> {{ order?.customerName || '' }} </a-descriptions-item>
                  <a-descriptions-item label="Quote Date"> {{ renderTime(order?.createdAt) }} </a-descriptions-item>
                  <a-descriptions-item label="Quote Number">{{ order.orderNumber }}</a-descriptions-item>
                </a-descriptions>

                <!-- 联系信息 -->
                <a-row :gutter="16" size="large">
                  <a-col :span="12">
                    <a-descriptions title="Customer Contact" :column="1" style="margin-top: 20px" bordered>
                      <a-descriptions-item label="Email:"> {{ order?.customerEmail || '' }} </a-descriptions-item>
                      <a-descriptions-item label="Name:"> {{ order?.customerName || '' }} </a-descriptions-item>
                      <a-descriptions-item label="Tel:"> {{ order?.customerTel || '' }} </a-descriptions-item>
                      <a-descriptions-item label="Add:"> {{ order?.customerAddress || '' }} </a-descriptions-item>
                    </a-descriptions>
                  </a-col>
                  <a-col :span="12">
                    <a-descriptions title="GSS Contact" :column="1" style="margin-top: 20px" bordered>
                      <a-descriptions-item label="Email:"> {{ gssSales.email }} </a-descriptions-item>
                      <a-descriptions-item label="Name:"> {{ gssSales.name }} </a-descriptions-item>
                      <a-descriptions-item label="Tel:"> {{ gssSales.tel }} </a-descriptions-item>
                      <a-descriptions-item label="Add:">{{ gssSales.address }}</a-descriptions-item>
                    </a-descriptions>
                  </a-col>
                </a-row>
              </a-card>

              <a-card>
                <h2 class="line">Order List</h2>
                <a-list :bordered="false" :split="true">
                  <a-list-item v-for="(record, index) in products" :key="index" :bordered="true">
                    <div>{{ record.siteName }}</div>
                    <address><icon-link /> {{ record.siteAddress }}</address>
                    <div style="margin-top: 20px; width: 1200px">
                      <a-descriptions
                        :column="3"
                        layout="horizontal"
                        table-layout="fixed"
                        :align="{ label: 'right' }"
                        :label-style="{ width: '160px' }"
                      >
                        <a-descriptions-item label="Product">{{ record.productType }}</a-descriptions-item>
                        <a-descriptions-item label="LMP">{{ record.carrierType }}</a-descriptions-item>
                        <a-descriptions-item label="Bandwidth">{{ record.bandwidth }}</a-descriptions-item>
                        <a-descriptions-item label="MRC (USD)">
                          {{ formatCurrency(record.broadbandRent + (record.cpeRent === -1 ? 0 : record.cpeRent)) }}
                        </a-descriptions-item>
                        <a-descriptions-item label="NRC (USD)">{{ formatCurrency(record.nrc) }}</a-descriptions-item>
                        <a-descriptions-item label="CPE">
                          {{ record.cpeRent !== -1 ? 'YES' : 'NO' }}
                        </a-descriptions-item>
                        <a-descriptions-item label="Additional LAN IP">
                          {{ record.ipType || 'NO' }}
                        </a-descriptions-item>
                        <a-descriptions-item label="Additional IP MRC">
                          {{ formatCurrency(record.ipRent) || 'None' }}
                        </a-descriptions-item>
                        <template v-if="record.advance">
                          <a-descriptions-item label="MTTR">
                            {{ record.mttr || 'None' }}
                          </a-descriptions-item>
                          <a-descriptions-item label="Interface">
                            {{ record.interfaceType || 'None' }}
                          </a-descriptions-item>
                          <a-descriptions-item label="Last Mile Technology">
                            {{ record.lastMileTechnology || 'None' }}
                          </a-descriptions-item>
                          <a-descriptions-item label="Lead Time">
                            {{ record.leadTime || 'None' }}
                          </a-descriptions-item>
                          <a-descriptions-item label="Quote Subtype">
                            {{ record.quoteSubtype || 'None' }}
                          </a-descriptions-item>
                        </template>
                        <a-descriptions-item label="Terms (Months)">{{ record.rentalMonths }}</a-descriptions-item>
                        <a-descriptions-item label="Total MRC">
                          {{
                            formatCurrency(
                              record.broadbandRent + (record.cpeRent === -1 ? 0 : record.cpeRent) + record.ipRent,
                            )
                          }}
                        </a-descriptions-item>
                        <a-descriptions-item label="Total NRC">{{ formatCurrency(record.nrc) }}</a-descriptions-item>
                        <a-descriptions-item label="Remark"> {{ record.remark }} </a-descriptions-item>
                      </a-descriptions>
                    </div>
                  </a-list-item>
                </a-list>
              </a-card>
              <a-card>
                <!-- 备注信息 -->
                <div class="remarks-section">
                  <a-list :bordered="false" :split="false">
                    <template #header><h2 class="line">Quotation Notes</h2></template>
                    <a-list-item>
                      <icon-check style="color: green; font-size: 24px" /> 1. Validity & Conditions: This quotation is
                      valid for one month. All offerings are subject to a pre-sale feasibility study and resource
                      availability. Resources are not reserved until order confirmation.
                    </a-list-item>
                    <a-list-item>
                      <icon-check style="color: green; font-size: 24px" /> 2. Delivery: Standard lead time is 4-6 weeks,
                      subject to resource confirmation and feasibility check after order confirmation.
                    </a-list-item>
                    <a-list-item>
                      <icon-check style="color: green; font-size: 24px" /> 3. Price Exclusions: The quoted price
                      excludes all additional charges, including but not limited to BMO, cross-connect, internal wiring,
                      third-party fees, overtime installation, and other extra provisioning costs. Any applicable
                      charges will be quoted separately upon order.
                    </a-list-item>
                    <a-list-item>
                      <icon-check style="color: green; font-size: 24px" /> 4. Service Details: Includes 24/7 support and
                      IP addresses as specified.
                    </a-list-item>
                    <a-list-item>
                      <icon-check style="color: green; font-size: 24px" /> 5. Proposal Basis: This proposal is subject
                      to conditions at the time of order, such as fibre availability, site planning, and network
                      capacity. Final delivery may differ from the pre-sales proposal.
                    </a-list-item>
                  </a-list>
                </div>
              </a-card>
            </a-space>
          </a-layout-content>
        </a-layout>
      </div>

      <!--footer-->
      <a-layout-footer>
        <a-row :gutter="24">
          <a-col :span="10" :offset="2">
            <a-card title="GOLD SUNSHINE INTERNATIONAL LIMITED" :bordered="false" class="footer-tit">
              <div class="company-info">
                <p class="company-address">Contact Us: sales@goldsunshine.net</p>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </a-layout-footer>
    </a-layout>
  </div>
</template>

<script setup lang="ts">
  import { h, ref, computed, reactive, onMounted } from 'vue';
  import type { Contact } from '@/api/types';
  import { Order, orderDetail, sendEmail } from '@/api/order-api'; // 导入接口
  import { Message } from '@arco-design/web-vue'; // 导入选项数据类型
  import dayjs from 'dayjs';
  import useLoading from '@/hooks/loading';
  import { useRouter, useRoute } from 'vue-router';
  import JsPDF from 'jspdf';
  import html2canvas from 'html2canvas';

  // PDF导出相关代码
  const showSaveBtn = ref<boolean>(true);
  const refPdf = ref<any>();
  const { loading, setLoading } = useLoading(true);
  const router = useRouter();
  const route = useRoute();
  const { id } = route.params;
  const order = ref<Order>({});
  const gssSales = reactive<Contact>({
    name: 'GSS, Sales Team',
    email: 'sales@goldsunshine.net',
    tel: '+86 10 5913 8888',
    address: 'RM208, No.550 Hongqiao Road, Xuhui District, Shanghai, China 200030',
  });

  const products = computed(() => {
    return order.value?.products || [];
  });

  const renderTime = (time: string, formatType = 'YYYY-MM-DD') => {
    return time ? dayjs(time).format(formatType) : '';
  };

  const formatCurrency = (num: number) => {
    if (num) {
      return num.toLocaleString('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
    }
    return '';
  };

  const fetchOrder = async (orderId: number) => {
    try {
      setLoading(true);
      const { result } = await orderDetail(orderId, 'demo');
      order.value = result;
    } catch (error) {
      Message.error({ content: error || 'Error', duration: 5 * 1000 });
    } finally {
      setLoading(false);
    }
  };

  // 生成PDF的方法
  const generatePdf = async (): Promise<File> => {
    // 1. 检查目标元素是否存在，不存在则抛出错误（由调用方catch捕获）
    if (!refPdf.value) {
      throw new Error('PDF目标元素不存在');
    }

    const canvas = await html2canvas(refPdf.value, { scale: 2, useCORS: true, logging: false });
    const imgData = canvas.toDataURL('image/jpeg', 0.95);
    const pdf = new JsPDF('p', 'mm', 'a4');
    const pageWidth = pdf.internal.pageSize.getWidth();
    const imgWidth = pageWidth;
    const imgHeight = (canvas.height / canvas.width) * imgWidth;

    pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);
    const binaryData = pdf.output('arraybuffer');
    const pdfBlob = new Blob([binaryData], { type: 'application/pdf' });
    return new File([pdfBlob], `${order.value?.orderNumber || 'unknown'}.pdf`, { type: 'application/pdf' });
  };

  // 生成PDF的方法
  const savePdf = async () => {
    // 1. 检查目标元素是否存在，不存在则抛出错误（由调用方catch捕获）
    if (!refPdf.value) {
      throw new Error('PDF目标元素不存在');
    }

    // 5. 用html2canvas生成画布（直接await，无需嵌套Promise）
    const canvas = await html2canvas(refPdf.value, { scale: 2, useCORS: true, logging: false });

    // 6. 转为图片数据
    const imgData = canvas.toDataURL('image/jpeg', 0.95);

    // 7. 初始化PDF
    const pdf = new JsPDF('p', 'mm', 'a4');
    const pageWidth = pdf.internal.pageSize.getWidth();

    // 8. 计算图片尺寸
    const imgWidth = pageWidth;
    const imgHeight = (canvas.height / canvas.width) * imgWidth;

    // 9. 插入图片
    pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);
    pdf.save(`${order.value?.orderNumber || 'unknown'}.pdf`);
  };

  const handleSendEmail = async () => {
    showSaveBtn.value = false;
    setLoading(true);
    try {
      // 生成PDF文件
      const pdfFile = await generatePdf();

      // 发送邮件
      const orderId = Array.isArray(id) ? parseInt(id[0], 10) : parseInt(id, 10);
      const protocol = await sendEmail(orderId, pdfFile);
      if (protocol.result) {
        Message.success({ content: 'Email sent successfully', duration: 5 * 1000 });
      } else {
        Message.error(`Email sent error: ${protocol.message}`);
      }
    } catch (error) {
      Message.error({ content: error || 'Error', duration: 5 * 1000 });
    } finally {
      showSaveBtn.value = true;
      setLoading(false);
    }
  };

  onMounted(() => {
    if (id) {
      const orderId = Array.isArray(id) ? parseInt(id[0], 10) : parseInt(id, 10);
      if (orderId) {
        fetchOrder(orderId);
      }
    }
  });
</script>

<style scoped>
  /* 表头单元格 - 居中对齐 */
  .arco-table-th.arco-table-cell-align-right {
    text-align: center !important;
  }
  :deep(.arco-layout-sider),
  :deep(.arco-layout-content),
  :deep(.arco-layout-footer) {
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size: 16px;
    text-align: left;
  }
  :deep(.arco-layout-sider) {
    width: 400px !important;
    padding: 10px;
    margin-right: 50px;
  }
  :deep(.arco-layout-sider-light) {
    background: #f9f9f9 !important;
  }
  :deep(.arco-layout-footer) {
    background: #e55d47;
    padding: 30px 0;
    margin-top: 50px;
  }
  :deep(.arco-card) {
    background: transparent;
  }
  .company-info {
    color: #fff;
    font-size: 18px;
    font-weight: 500;
  }
  .footer-tit :deep(.arco-card-header-title) {
    color: #fff;
    font-size: 24px;
    font-weight: bold;
  }
  .rss-tit {
    color: #fff;
    font-size: 24px;
    font-weight: bold;
  }
  .btn {
    min-height: 60px;
    padding: 20px 50px;
    border-radius: 30px;
    background: transparent;
    background-image: linear-gradient(135deg, #ffdf73 0%, #ff8534 60%);
    font-weight: 500;
    color: #fff;
    font-size: 20px;
  }
  .line {
    border-bottom: 1px solid #666;
    padding-bottom: 20px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .line::after {
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100px;
    height: 2px;
    background: #df0000;
  }
  .remarks-section :deep(.arco-list) {
    font-size: 20px;
  }
  :deep(.arco-card-bordered) {
    border: 1px solid #e2dcdc;
    border-radius: 15px 15px 15px 15px;
    box-shadow: 0 0 60px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }
  :deep(.arco-card-size-medium .arco-card-header-title) {
    font-size: 20px;
    font-weight: bold;
  }
  :deep(.arco-card-header) {
    height: 60px;
    border-radius: 15px 15px 0 0;
  }
  .company-address {
    font-size: 24px;
    font-weight: 500;
  }
</style>
